<!-- 健康雷达图 -->

<template>
  <div class="health-radar">

    <div class="totalScore">总得分:
      <span class="totalScore-totalScoreValue">{{totalScore}}</span>
    </div>
    <div ref="radarChart" class="radar-chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'HealthRadar',
  data() {
    return {
      chart: null,
      scoreDict: {},
      indicatorOrder: [],

      //总得分
      totalScore: 0,
    }
  },
  props: {
    healthScoreData: {
      type: Object,
      default: () => null
    }
  },
  watch: {
    // 监听数据变化，更新图表
    healthScoreData: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initChart()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },

  mounted() {
    this.$nextTick(() => {
      if (this.healthScoreData) {
        this.initChart()
      }
      // 监听窗口大小变化，自适应调整图表
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    // 组件销毁前清理图表实例和事件监听
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initChart() {
      // 如果没有数据，不初始化图表
      if (!this.healthScoreData) {
        return
      }

      let scoreDict = {}
      const result = this.healthScoreData

      // 映射数据字典，按照指标顺序
      scoreDict = {
        '电气系统': result.scoreElectrical || 0,
        '温度系统': result.scoreTemperature || 0,
        '维修历史': result.scoreFault || 0,
        '告警频率': result.scoreAlarm || 0
      };
      this.totalScore = result.scoreTotal || 0;

      // 初始化图表实例
      this.chart = echarts.init(this.$refs.radarChart)

      // 定义指标顺序（必须与 scoreDict 的键顺序一致）
      const indicatorOrder = ['电气系统', '温度系统', '维修历史', '告警频率']

      // 雷达图配置选项
      const option = {
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#409EFF',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 13
          },
          padding: [10, 15],
          formatter: (params) => {
            // 定义每个指标对应的颜色
            const colorMap = {
              '电气系统': '#409EFF',
              '温度系统': '#67C23A',
              '维修历史': '#E6A23C',
              '告警频率': '#F56C6C'
            }
            
            // 显示所有类别的评分
            let tooltipContent = '<div style="font-weight: 600; color: #2d4a6b; margin-bottom: 8px;">健康评分详情</div>'
            this.indicatorOrder.forEach((indicatorName, index) => {
              const value = this.scoreDict[indicatorName] || 0
              const color = colorMap[indicatorName] || '#666'
              
              // 根据分数设置数值颜色
              let valueColor = '#67C23A' // 绿色 - 高分
              if (value < 60) {
                valueColor = '#F56C6C' // 红色 - 低分
              } else if (value < 80) {
                valueColor = '#E6A23C' // 橙色 - 中分
              }
              
              tooltipContent += `<div style="margin: 4px 0;">
                <span style="color: ${color}; font-weight: 500;">${indicatorName}</span>
                <span style="color: ${valueColor}; font-weight: 600; margin-left: 8px;">${value}分</span>
              </div>`
            })
            return tooltipContent
          }
        },
        radar: {
          indicator: indicatorOrder.map(key => {
            return { name: key, max: 100 }
          }),
          center: ['50%', '50%'],
          radius: '55%',
          name: {
            textStyle: {
              color: 'black',
              fontSize: 12
            }
          },
          splitArea: {
            areaStyle: {
              color: 'rgba(250, 250, 250, 0.3)'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          }
        },
        series: [
          {
            name: '健康评分',
            type: 'radar',
            data: [
              {
                // value 数组必须按照 indicator 的顺序排列
                value: indicatorOrder.map(key => scoreDict[key] || 0),
                name: '当前评分',
                areaStyle: {
                  color: 'rgba(64, 158, 255, 0.3)'
                },
                lineStyle: {
                  color: '#409EFF',
                  width: 2
                },
                itemStyle: {
                  color: '#409EFF'
                }
              }
            ]
          }
        ]
      }

      // 保存 scoreDict 到组件实例，供 tooltip 使用
      this.scoreDict = scoreDict
      this.indicatorOrder = indicatorOrder

      // 设置配置项并渲染图表
      this.chart.setOption(option)
    },
    handleResize() {
      // 窗口大小改变时重新调整图表大小
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.health-radar {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .totalScore {
    position: absolute;
    // 居中
    top: 5%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
    font-weight: bold;
    color: #333;

    &-totalScoreValue {
      position: relative;
      top: 4px;
      //倾斜的字体
      font-size: 30px;
      font-style: italic;
      color: #67c23a;
    }
  }

}

.radar-chart {
  width: 100%;
  height: 100%;
  min-height: 0;
}
</style>